﻿using System;
using System.Activities;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace TCM.Controllers
{
    public class CourseController : Controller
    {
        #region Common Variables
        private TCMContext db = new TCMContext();
        #endregion

        #region construction methods
        public CourseController()
        {
            ViewBag.SelectDayOfWeek = this.SelectListDayOfWeek;
            ViewBag.SelectListInstructors = this.SelectListInstructors;
            ViewBag.SelectListRooms = this.SelectListRooms;
            ViewBag.SelectListRquiredExam = this.SelectListRquiredExam;
            ViewBag.SelectedListSubjects = this.SelectedListSubjects;
            ViewBag.SelectListLevels = this.ListLevel;
        }
        #endregion

        #region Course methods

        //
        // GET: /Course/
        public ActionResult Index()
        {
            var coursebases = db.COURSEBASEs.Include(c => c.INSTRUCTORBASE).Include(c => c.LEVELBASE);

            return View(coursebases.ToList());
        }

        //
        // GET: /Course/Details/5
        public ActionResult Details(Guid? id = null)
        {
            COURSEBASE coursebase = db.COURSEBASEs.Find(id);
            if (coursebase == null)
            {
                return HttpNotFound();
            }
            return View(coursebase);
        }

        //
        // GET: /Course/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Course/Create
        [HttpPost]
        public ActionResult Create(COURSEBASE coursebase)
        {
            if (ModelState.IsValid)
            {
                coursebase.COURSEID = Guid.NewGuid();
                var svData = db.COURSEBASEs.Add(coursebase);
                db.SaveChanges();
                //return RedirectToAction("Index");
                return RedirectToAction("edit/" + svData.COURSEID.ToString());
            }


            return View(coursebase);
        }

        //
        // GET: /Course/Edit/5
        public ActionResult Edit(Guid? id = null)
        {
            if (!id.HasValue)
            {
                return View();
            }
            COURSEBASE coursebase = db.COURSEBASEs
                .Include(p => p.AGENDABASEs)
                .Include(p => p.COURSESCHEDULEBASEs)
                .Include(p => p.LEVELBASE)
                .Where<COURSEBASE>(x => x.COURSEID.Equals(id.Value))
                .FirstOrDefault();
            
            if (coursebase == null)
            {
                return HttpNotFound();
            }
            
           

            ViewBag.SelectListRquiredExam = this.SelectListRquiredExam;

            foreach (var SchdeduleLine in coursebase.COURSESCHEDULEBASEs)
            {
                if (SchdeduleLine.DAYID.HasValue)
                {
                    var DayName = this.SelectListDayOfWeek
                        .Where(x => x.Value == SchdeduleLine.DAYID.Value.ToString())
                        .FirstOrDefault();
                    SchdeduleLine.DayName = DayName.Text;
                }
            }

            return View(coursebase);
        }

        public ActionResult GenerateScheduleCourse(Guid? id = null)
        {
            var coursebase = db.COURSEBASEs.Find(id);
            InOutArgument<COURSEBASE> ff = new InOutArgument<COURSEBASE>();
            foreach (var item in coursebase.COURSESCHEDULEBASEs)
            {
                var day = db.MAPSTRINGBASEs.Find(item.DAYID);

                item.DayName = day.DISPLAYVALUE;
            }

            var input = new Dictionary<string, object> { { "eEntity", coursebase } };


            WorkflowInvoker.Invoke(new Workflows.AgendaOnCreating(), input);

            db.SaveChanges();
            return RedirectToAction("edit/" + id.ToString());
        }

        //
        // POST: /Course/Edit/5
        [HttpPost]
        public ActionResult Edit(COURSEBASE coursebase)
        {

            #region Update Status
            #region Schedule
            var UpdateSchedules = from x in coursebase.COURSESCHEDULEBASEs
                                  where x.DeletedByUI == false
                                        && x.COURSESCHEDULEID != Guid.Empty
                                  select x;
            foreach (var UpdateSchedule in UpdateSchedules)
            {
                db.Entry(UpdateSchedule).State = EntityState.Modified;
            }
            #endregion

            #region Agenda
            var UpdateAgendas = from x in coursebase.AGENDABASEs
                                where x.DeleteByUI == false
                                      && x.AGENDAID != Guid.Empty
                                select x;
            foreach (var UpdateAgenda in UpdateAgendas)
            {
                db.Entry(UpdateAgenda).State = EntityState.Modified;
            }
            #endregion

            #endregion

            #region New status

            #region Schedule
            var NewSchedules = from x in coursebase.COURSESCHEDULEBASEs
                               where x.COURSESCHEDULEID.Equals(Guid.Empty)
                               select x;
            foreach (var NewSchedule in NewSchedules)
            {
                NewSchedule.COURSESCHEDULEID = Guid.NewGuid();
                NewSchedule.COURSEID = coursebase.COURSEID;
                db.Entry(NewSchedule).State = EntityState.Added;

            }
            #endregion

            #region Agenda
            var NewAgendas = from x in coursebase.AGENDABASEs
                             where x.AGENDAID.Equals(Guid.Empty)
                             select x;
            foreach (var NewAgenda in NewAgendas)
            {
                NewAgenda.AGENDAID = Guid.NewGuid();
                NewAgenda.COURSEID = coursebase.COURSEID;
                db.Entry(NewAgenda).State = EntityState.Added;
            }
            #endregion

            #endregion

            

            

            #region Delete Status
            #region avoid the error with delete
            int DeleteAgendaCount = coursebase.AGENDABASEs.Where<AGENDABASE>(x => x.DeleteByUI == true).Count();
            int DeleteScheduleAcount = coursebase.COURSESCHEDULEBASEs.Where<COURSESCHEDULEBASE>(x => x.DeletedByUI == true).Count();
            if ((DeleteAgendaCount + DeleteScheduleAcount) > 0)
            {
                db.COURSEBASEs.Attach(coursebase);
            }
            #endregion
            #region schedule

            var DeleteScheduleIDs = (from x in coursebase.COURSESCHEDULEBASEs
                                     where x.DeletedByUI == true
                                     select x.COURSESCHEDULEID).ToList();
            foreach (var DeleteScheduleID in DeleteScheduleIDs)
            {
                var ScheduleDeleted = coursebase
                    .COURSESCHEDULEBASEs
                    .Where<COURSESCHEDULEBASE>(x => x.DeletedByUI == true)
                    .FirstOrDefault();
                db.COURSESCHEDULEBASEs.Attach(ScheduleDeleted);
                db.Entry(ScheduleDeleted).State = EntityState.Deleted;
            }

            #endregion
            #region agenda
            var DeleteAgendaIDs = (from x in coursebase.AGENDABASEs
                                   where x.DeleteByUI == true
                                   select x.AGENDAID).ToList();
            foreach (var DeleteAgendaID in DeleteAgendaIDs)
            {
                var AgendaDeleted = coursebase
                    .AGENDABASEs
                    .Where<AGENDABASE>(p => p.AGENDAID.Equals(DeleteAgendaID)).FirstOrDefault();
                db.AGENDABASEs.Attach(AgendaDeleted);
                db.Entry(AgendaDeleted).State = EntityState.Deleted;

            }
            #endregion
            #endregion


            db.Entry(coursebase).State = EntityState.Modified;

            //save data to database
            db.SaveChanges();


            //return View(coursebase); 
            return RedirectToAction("edit/" + coursebase.COURSEID.ToString());

        }

        //
        // GET: /Course/Delete/5
        public ActionResult Delete(Guid? id = null)
        {
            COURSEBASE coursebase = db.COURSEBASEs.Find(id);
            if (coursebase == null)
            {
                return HttpNotFound();
            }
            return View(coursebase);
        }

        //
        // POST: /Course/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(Guid id)
        {
            COURSEBASE coursebase = db.COURSEBASEs.Find(id);
            db.COURSEBASEs.Remove(coursebase);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        #endregion

        #region Method Partial

        public ActionResult EditRelatedCourseSchedule()
        {
            return PartialView("EditRelatedCourseSchedule");
        }
        public ActionResult _NewRelatedAgenda()
        {
            return PartialView("_RelatedAgenda");
        }
        

        #endregion

        #region helper methods and properties
         
        /// <summary>
        /// this set the 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RemoveSchedule(Guid? id = null)
        {
            if (id.HasValue)
            {
                //System.Diagnostics.Debugger.Break();
                var deleteinstance = db.COURSESCHEDULEBASEs.Find(id.Value);
                deleteinstance.DeletedByUI = true;
                if (TryUpdateModel(deleteinstance))
                {                    
                    return View(deleteinstance);
                }
                //db.COURSESCHEDULEBASEs.Remove(deleteinstance);
                //db.SaveChanges();
            }
            return null;
            //return "dsds";// Json(new { success = true });
        }

        [ActionName(name:"deleteme")]
        public ActionResult deleteme(Guid?id=null)
        {

            COURSESCHEDULEBASE c = db.COURSESCHEDULEBASEs.Find(id);
            Guid courseid = c.COURSEID.Value;
            db.COURSESCHEDULEBASEs.Remove(c);
            //db.SaveChanges();
            var t = db.COURSESCHEDULEBASEs
                .Where<COURSESCHEDULEBASE>(x => x.COURSEID.Value.Equals(courseid))
                .AsEnumerable<COURSESCHEDULEBASE>();
           return PartialView("EditRelatedCourseSchedule");
            
        }

        public IEnumerable<MAPSTRINGBASE> DayOfWeek
        {
            get
            {
                var dbDayOFWeek = db.MAPSTRINGBASEs
               .Where<MAPSTRINGBASE>
               (x => x.ATTRIBUTENAME.ToLower().Equals("dayid") &&
                   x.ENTITYNAME.ToLower().Equals("courseschedulebase")).ToList();
                return dbDayOFWeek;
            }
        }
        /// <summary>
        /// Select DayOfWeek
        /// </summary>
        public SelectList SelectListDayOfWeek
        {
            get
            {
                return new SelectList(this.DayOfWeek, "MAPSTRINGID", "DISPLAYNAME");
            }
        }

        public SelectList SelectListInstructors
        {
            get
            {
                return new SelectList(db.INSTRUCTORBASEs, "INSTRUCTORID", "NAME");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public SelectList SelectListRooms
        {
            get
            {
                return new SelectList(db.ROOMBASEs, "RoomID", "Name");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public SelectList SelectListRquiredExam
        {
            get
            {
                var dbRequiredExam = db.MAPSTRINGBASEs
                                     .Where<MAPSTRINGBASE>
                                     (x => x.ATTRIBUTENAME.ToLower().Equals("EXAMREQUIRED".ToLower()) &&
                                         x.ENTITYNAME.ToLower().Equals("course".ToLower())).ToList();

                return new SelectList(dbRequiredExam, "MAPSTRINGID", "DISPLAYNAME");
            }
        }

        public SelectList SelectedListSubjects
        {
            get
            {
                return new SelectList(db.SUBJECTBASEs, "SUBJECTID", "NAME");
            }
        }
        public SelectList ListLevel
        {
            get
            {
                return new SelectList(db.LEVELBASEs, "levelid", "NAME");
            }
        }
        

        public string RelatedSelectListSubject(Guid? id = null)
        {
            if (!id.HasValue) return string.Empty;

            //var dbSubjectLevels = null;
            //(from xSubjectlevel in db.SUBJECTLEVELBASEs
            //                       where xSubjectlevel.SUBJECTID.Value.Equals(id.Value)
            //                       select new { Value = xSubjectlevel.SUBJECTLEVELID, Text = xSubjectlevel.NAME }
            //                       ).ToArray();


            return "";///new JavaScriptSerializer().Serialize(dbSubjectLevels);
            // return null;
        }

        //public SelectList LoadTimeAMPM
        //{
        //    get
        //    {
        //        return null;
        //    }
        //}
        #endregion

    }
}